package com.bobo.controller.front.topic;

import com.alibaba.fastjson.JSON;
import com.bobo.annotations.RequestBody;
import com.bobo.annotations.RequestMapping;
import com.bobo.annotations.RequestMethod;
import com.bobo.controller.base.BaseServlet;
import com.bobo.dto.Page;
import com.bobo.model.*;
import com.bobo.service.category.CategoryServiceImpl;
import com.bobo.service.category.ICategoryService;
import com.bobo.service.favourite.FavouriteServiceImpl;
import com.bobo.service.favourite.IFavouriteService;
import com.bobo.service.message.IMessageService;
import com.bobo.service.message.MessageServiceImpl;
import com.bobo.service.photo.IPhotoService;
import com.bobo.service.photo.PhotoServiceImpl;
import com.bobo.service.report.IReportService;
import com.bobo.service.report.ReportServiceImpl;
import com.bobo.service.tag.ITagService;
import com.bobo.service.tag.TagServiceImpl;
import com.bobo.service.topic.ITopicService;
import com.bobo.service.topic.TopicServiceImpl;
import com.bobo.service.topicTag.ITopicTagService;
import com.bobo.service.topicTag.TopicTagServiceImpl;
import com.bobo.util.UploadFiles;


import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Created by bobo on 16-10-30.
 */
@WebServlet(name = "topic",urlPatterns = {"/topic/*"})
public class TopicController extends BaseServlet {

    private ITopicService topicService = new TopicServiceImpl();
    private IPhotoService photoService = new PhotoServiceImpl();
    private UploadFiles uploadFiles = new UploadFiles();
    private ICategoryService categoryService = new CategoryServiceImpl();
    private ITopicTagService topicTagService = new TopicTagServiceImpl();
    private IFavouriteService favouriteService = new FavouriteServiceImpl();
    private IReportService reportService = new ReportServiceImpl();

    @RequestMapping("/add")
    public String add(HttpServletRequest request){
        List<Category> categories = categoryService.getCategories(1);
        request.setAttribute("categories",categories);
        return "jsp/front/topic/add";
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public String add(HttpServletRequest request, HttpServletResponse response){
        try {
            Map<String, Object[]> map = uploadFiles.upload(request);
            Topic topic = new Topic();

            User user = (User) request.getSession().getAttribute("user");
            if(user==null){
                return "redirect:/user/login";
            }
            topic.setUser(user);

            Object[] titles = map.get("title");
            Object[] categoryIds = map.get("categoryId");
            Object[] tags = map.get("tag");
            Object[] describes = map.get("describe");
            Object[] contents = map.get("content");
            Object[] objs = map.get("fileName");

            if (titles == null || categoryIds == null || tags == null
                    || describes == null || contents == null ||
                    titles.length < 0 || categoryIds.length < 0 ||
                    tags.length < 0 || describes.length < 0 || contents.length < 0) {
                return "error";
            }
            String title = (String) titles[0];
            topic.setTitle(title);
            String categoryId = (String) categoryIds[0];
            Category category = categoryService.getById(Integer.valueOf(categoryId));
            topic.setCategory(category);

            String describe = (String) describes[0];
            topic.setDescribe(describe);
            String content = (String) contents[0];
            topic.setContent(content);

            if (objs!=null && objs.length > 0) {
                Photo photo = new Photo();
                photo.setImg((String) objs[0]);
                photo.setStatus(3);
                Integer pid = photoService.create(photo);
//                Photo photo1 = photoService.getPhoto(pid);
                photo.setId(pid);
                topic.setPhoto(photo);
            }else {
                Photo photo = category.getPhoto();
                topic.setPhoto(photo);
            }
            Integer topicid = topicService.create(topic);

            for (Object tagid:tags){
                TopicTag topicTag = new TopicTag();
                topicTag.setTagId(Integer.valueOf((String) tagid));
                topicTag.setTopicId(topicid);
                topicTagService.create(topicTag);
            }
            return "redirect:/index/blog";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "error";
    }

    @RequestBody
    @RequestMapping("/del")
    public String del(HttpServletRequest request, HttpServletResponse response){
        int id = Integer.parseInt(request.getParameter("id"));
        Topic topic = topicService.getById(id);
        topic.setStatus(2);
        topicService.update(topic);
        return "true";
    }

    @RequestMapping("/upd")
    public String upd(HttpServletRequest request){
        int id = Integer.parseInt(request.getParameter("id"));
        Topic topic = topicService.getById(id);

        ICategoryService categoryService = new CategoryServiceImpl();
        List<Category> categories = categoryService.getCategories(1);
        request.setAttribute("categories",categories);

        ITopicTagService topicTagService = new TopicTagServiceImpl();
        List<Tag> tag = topicTagService.getTags(id);
        topic.setTags(tag);

        request.setAttribute("topic",topic);
        return "jsp/front/topic/upd";
    }

    @RequestMapping(value = "/upd",method = RequestMethod.POST)
    public String updd(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object[]> map = uploadFiles.upload(request);
            Object[] ids = map.get("id");
            Object[] titles = map.get("title");
            Object[] categoryIds = map.get("categoryId");
            Object[] tags = map.get("tag");
            Object[] describes = map.get("describe");
            Object[] contents = map.get("content");
            Object[] objs = map.get("fileName");

            int id = Integer.parseInt((String )ids[0]);
            Topic topic = topicService.getById(id);
            if (titles == null || categoryIds == null || tags == null
             || describes == null || contents == null ||
             titles.length < 0 || categoryIds.length < 0 ||
             tags.length < 0 || describes.length < 0 || contents.length < 0) {
                return "error";
            }

            User user = (User) request.getSession().getAttribute("user");
            topic.setUser(user);

            String title = (String) titles[0];
            topic.setTitle(title);
            String categoryId = (String) categoryIds[0];
            Category category = categoryService.getById(Integer.valueOf(categoryId));
            topic.setCategory(category);

            String describe = (String) describes[0];
            topic.setDescribe(describe);
            String content = (String) contents[0];
            topic.setContent(content);

            if (objs!=null && objs.length > 0) {
                if(topic.getPhoto().getId()==topic.getCategory().getPhoto().getId()){
                    Photo photo = new Photo();
                    photo.setImg((String) objs[0]);
                    photo.setStatus(3);
                    Integer pid = photoService.create(photo);
                    photoService.getPhoto(pid);
                }else {
                    uploadFiles.delFile(request,topic.getPhoto().getImg());
                    Photo photo = topic.getPhoto();
                    photo.setImg((String) objs[0]);
                    photoService.update(photo);
                }
            }

            topicService.update(topic);
            TopicTag topicTag = new TopicTag();
            topicTag.setTopicId(topic.getId());
            topicTagService.delete(topicTag);
            for (Object tagId:tags){
                topicTag.setTagId(Integer.valueOf((String) tagId));
                topicTag.setTopicId(topic.getId());
                topicTagService.create(topicTag);
            }
            return "redirect:/index/blog";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "error";
    }

    @RequestMapping("/get")
    public String get(HttpServletRequest request){
        ICategoryService categoryService = new CategoryServiceImpl();
        List<Category> categories = categoryService.getCategories(1);
        request.setAttribute("categories",categories);

        ITagService tagService = new TagServiceImpl();
        List<Tag> tags = tagService.getTags(0,0,1);
        request.setAttribute("tags",tags);

        //推荐文章

        List<Topic> topics = topicService.getTops(1);
        request.setAttribute("topics",topics);
        int current = 1;
        int pageSize = 5;

        if(request.getParameter("current") != null) {
            current = Integer.parseInt(request.getParameter("current"));
        }

        if(request.getParameter("pageSize") != null) {
            pageSize = Integer.parseInt(request.getParameter("pageSize"));
        }

        int id = Integer.parseInt(request.getParameter("id"));

        ITopicTagService topicTagService = new TopicTagServiceImpl();
        List<Tag> tag = topicTagService.getTags(id);
        //评论
        IMessageService messageService = new MessageServiceImpl();
        Page<Message> page = messageService.getMessagesByTopic(id, current, pageSize, 1);

        Topic topic = topicService.getById(id);
        topic.setTags(tag);


        topic.setHits(topic.getHits() + 1);
        topicService.update(topic);

        boolean isFav = false;

        List<Integer> reps = new ArrayList<>();
        if(request.getSession().getAttribute("user") != null) {
            User user = (User)request.getSession().getAttribute("user");
            Favourite f = new Favourite();
            f.setTopicId(id);
            f.setUserId(user.getId());

            isFav =  favouriteService.query(f);

            List<Message> messages = reportService.getReportByUser(user, topic);

            for (Message message : messages) {
                reps.add(message.getId());
            }
        }



        request.setAttribute("reps", reps);
        request.setAttribute("isFav", isFav);
        request.setAttribute("page",page);
        request.setAttribute("topic",topic);
        return "jsp/front/topic/get";
    }


    @RequestBody
    @RequestMapping("/getTags")
    public String getTags(HttpServletRequest request, HttpServletResponse response){
        ITagService tagService = new TagServiceImpl();
        int id = Integer.parseInt(request.getParameter("id"));
        List<Tag> tags = tagService.getTags(id, 1);
        return JSON.toJSONString(tags);
    }

    @RequestBody
    @RequestMapping("/query")
    public String query(HttpServletRequest request, HttpServletResponse response){

        int id = Integer.parseInt(request.getParameter("id"));
        User user = (User) request.getSession().getAttribute("user");
        Favourite favourite = new Favourite();
        favourite.setTopicId(id);
        favourite.setUserId(user.getId());
        boolean query = favouriteService.query(favourite);
        if(query){
            return "true";
        }else {
            return "false";
        }
    }
}
